package com.codi.api.interceptor;

import com.codi.api.security.UserUtil;
import com.codi.base.exception.ExceptionHandler;
import com.codi.bus.core.domain.User;
import com.codi.bus.core.service.UserService;
import com.codi.message.constant.ErrorConst;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 校验请求是否需要有机构权限
 *
 * @author shi.pengyan
 * @version 1.0 2017-09-05 13:27
 * @since 1.0
 */
@Slf4j
public class ValidateOrganRoleInterceptor implements HandlerInterceptor {

    @Autowired
    private UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        Long userId = UserUtil.getLoginUserId();

        User user = userService.getUser(userId);
        if (!user.getIsOrg()) {
            ExceptionHandler.publish(ErrorConst.ORGAN_ROLE_PERMISSION_ONLY);
            return false;
        }

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
